﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using IHISCETeim.Model;
using IHISCETeim.BLL;
using IHISCETeim.Library;
using System.Data;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Configuration;

using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.POIFS.FileSystem;
using NPOI.SS.UserModel;


namespace IHISCETeim.Web.Export
{
    public abstract class ExportPageBase : System.Web.UI.Page
    {

        protected void PageBase_Error(object sender, EventArgs e)
        {
            Exception currentError = Server.GetLastError();
            try
            {
                if (currentError == null)
                {
                    return;
                }
                //if (currentError is WebException)
                //{
                //    ((WebException)currentError).Handle();
                //}
                //else
                //{
                    string friendlyMsg = currentError.Message;
　//　如果程序处于Debug状态，则直接在页面显示具体不正确信息，便于调试
                    friendlyMsg = currentError.Message + "<br　/>Stack:" + currentError.StackTrace;
                    Response.Write(friendlyMsg);


                //}
            }
            finally
            {
                SLogInfo obj = new SLogInfo();
                obj.LogType = "错误";
                obj.DWZRef = this.DWZRef;
                obj.RealName = User.RealName;
                obj.OpOldObj = currentError.Message;

                SLogController.Add(obj);
            }

            Server.ClearError();
        }
        protected override void OnInit(EventArgs e)
        {
            this.Error += new System.EventHandler(this.PageBase_Error);
            base.OnInit(e);
            //验证权限规证
            if (!User.IsSuperAdmin)
            {
                //if (MustLogin)
                //{
                //    if (!Request.IsAuthenticated)
                //        throw new NeedLoginException("请先登陆");
                //}

                if (!HasPower(PowerKey))
                {
                    throw new Exception("您没有权限进入此页面");
                }
            }
        }
        public OUserInfo User { get { return OUserController.CurrentUser; } }
        private string _DWZRef = "";
        /// <summary>
        /// DWZ框架中的页面ID，用于服务器转回navTabId可以把那个navTab标记为reloadFlag=1, 下次切换到那个navTab时会重新载入内容
        /// </summary>
        protected virtual string DWZRef
        {
            get { return ""; }
        }
        /// <summary>
        /// 访问此页面所属的权限
        /// </summary>       
        protected virtual Permission[] PowerKey
        {
            get
            {
                return new Permission[] { Permission.none };
            }
        } 
        public bool HasPower(Permission per)
        {
            return HasPower(new Permission[] { per });
        }
        /// <summary>
        /// 权限判断
        /// </summary>
        /// <param name="per"></param>
        /// <returns></returns>
        public bool HasPower(Permission[] per)
        {
            return HasPower(this.DWZRef, per);
        }

        public bool HasPower(string DWZRel, Permission[] per)
        {
            return HasPower(DWZRel, per, User);
        }
        public bool HasPower(string DWZRel, Permission[] per, OUserInfo objUser)
        {
            if (objUser.IsSuperAdmin)
                return true;
            if (per.Length <= 1)
            {
                if (per[0] == Permission.none)
                    return true;
            }
            int MenuId = 0;
            List<OMenuInfo> allMenuDT = OMenuController.GetAllOMenu2();
            MenuId = allMenuDT.Find(e => e.DWZRel.ToLower() == DWZRel.ToLower()).MenuId;

            List<OMenuPermissionInfo> alper = ORoleController.GetPermissionByRoleId(objUser.RoleId);

            bool r = false;
            foreach (Permission p in per)
            {
                OMenuPermissionInfo obj = alper.Find(e => e.MenuId == MenuId && e.PermissionTag == p.ToString());

                r = obj == null ? false : true;
                if (r)
                    break;
            }

            return r;
        }

        #region 目录相关
      
        /// <summary>
        /// 当前应用程序根目录
        /// </summary>
        public string ApplicationPath
        {
            get
            {

                return HttpContext.Current.Request.PhysicalApplicationPath;
            }
        }
        /// <summary>
        /// 导出模板目录所在,相对路径
        /// </summary>
        public string XlsTemplateFolderPath
        {
            get
            {
                return "/ExportExcel/XlsTemplate/";
            }
        }
        /// <summary>
        /// 导出文件临时存储目录
        /// </summary>
        public string DownLoadTempFolderPath
        {
            get {
                return "/ExportExcel/downloadtemp/";
            }
        }
        /// <summary>
        /// 需导出的模板名称.一定是要放在　[XlsTemplateFolderPath]所指目录下
        /// 如 融资租赁报单情况汇总表.xls
        /// </summary>
        protected abstract string xlsTemplateFileName
        {
            get;
        }
        /// <summary>
        ///要导出的EXCEL　的工作表名
        ///
        /// </summary>
        protected abstract string SheetName
        {
            get;
        }

       
        #endregion

        #region 导出代码相关
        protected HSSFWorkbook hssfworkbook;
        /// <summary>
        /// 初始化需导出的文件
        /// 加载模板
        /// </summary>
        protected void InitializeWorkbook()
        {
            //read the template via FileStream, it is suggested to use FileAccess.Read to prevent file lock.
            //book1.xls is an Excel-2007-generated file, so some new unknown BIFF records are added. 

            string xlstempletePath = ApplicationPath + XlsTemplateFolderPath + xlsTemplateFileName;

            FileStream file = new FileStream(xlstempletePath, FileMode.Open, FileAccess.Read);

            hssfworkbook = new HSSFWorkbook(file);

            //create a entry of DocumentSummaryInformation
            DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
            dsi.Company = "IHISCE";
            hssfworkbook.DocumentSummaryInformation = dsi;

            //create a entry of SummaryInformation
            SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
            si.Subject = "信息化平台导出系统";
            hssfworkbook.SummaryInformation = si;
        }
        /// <summary>
        /// 设置文件名
        /// </summary>
        /// <param name="oldFileName"></param>
        /// <returns></returns>
        protected virtual string GetXlsFileName(string oldFileName)
        {
            return oldFileName;
        }

        /// <summary>
        /// 写入XLS文件到临时存放目录
        /// </summary>
        protected void WriteToFile()
        {
            string xlstempletePath = ApplicationPath + XlsTemplateFolderPath + xlsTemplateFileName;
            FileInfo f = new System.IO.FileInfo(xlstempletePath);
            //设置导出的文件名
            string exportFileName =GetXlsFileName( DateTime.Now.ToString("yyyyMMdd_HHmmss")+f.Name);
            //
            string exportPath = ApplicationPath + DownLoadTempFolderPath + exportFileName;
            //Write the stream data of workbook to the root directory
            //FileStream file = new FileStream(exportPath, FileMode.Create);

            using(FileStream file = new FileStream(exportPath, FileMode.Create))
            {
                hssfworkbook.Write(file);
                file.Close();

                //
                Response.Clear();
                Response.Buffer = true;
                HttpContext context = HttpContext.Current;
                string filepath = exportPath;    //文件路径          
                int alllen = filepath.Length;
                int fileanemstate = filepath.LastIndexOfAny(new char[] { '/' });
                string filename = filepath.Substring(fileanemstate + 1, alllen - fileanemstate - 1);
                //设置输出文件类型为DWF格式
                Response.ContentType = "Application/ms-excel";
                //添加下载头信息，并设置下载文件名称
              //  filename＝ new String(filename.getBytes("iso-8859-1"),"utf-8");
                Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(filename));
                //下载文件
                Response.TransmitFile(filepath);
                Response.End();
            }
           
        }
        /// <summary>
        /// 向工作表插入行
        /// </summary>
        /// <param name="sheet"></param>
        /// <param name="插入行"></param>
        /// <param name="插入行总数"></param>
        /// <param name="源格式行"></param>
        protected void MyInsertRow(HSSFSheet sheet, int 插入行, int 插入行总数, HSSFRow 源格式行)
        {
            #region 批量移动行
            sheet.ShiftRows
            (
            插入行,                                 //--开始行
            sheet.LastRowNum,                       //--结束行
            插入行总数,                             //--移动大小(行数)--往下移动
            true,                                   //是否复制行高
            false,                                  //是否重置行高
            true                                    //是否移动批注
            );
            #endregion

            #region 对批量移动后空出的空行插，创建相应的行，并以插入行的上一行为格式源(即：插入行-1的那一行)
            for (int i = 插入行; i < 插入行 + 插入行总数 - 1; i++)
            {
                HSSFRow targetRow = null;
                HSSFCell sourceCell = null;
                HSSFCell targetCell = null;

                targetRow = (HSSFRow)sheet.CreateRow(i + 1);

                for (int m = 源格式行.FirstCellNum; m < 源格式行.LastCellNum; m++)
                {
                    sourceCell = (HSSFCell)源格式行.GetCell(m);
                    if (sourceCell == null)
                        continue;
                    targetCell = (HSSFCell)targetRow.CreateCell(m);
                    //targetCell.Encoding = sourceCell.Encoding;
                    targetCell.CellStyle = sourceCell.CellStyle;
                    targetCell.SetCellType(sourceCell.CellType);
                }
                //CopyRow(sourceRow, targetRow);
                //Util.CopyRow(sheet, sourceRow, targetRow);
            }
            HSSFRow firstTargetRow = (HSSFRow)sheet.GetRow(插入行);
            HSSFCell firstSourceCell = null;
            HSSFCell firstTargetCell = null;
            for (int m = 源格式行.FirstCellNum; m < 源格式行.LastCellNum; m++)
            {
                firstSourceCell = (HSSFCell)源格式行.GetCell(m);
                if (firstSourceCell == null)
                    continue;
                firstTargetCell = (HSSFCell)firstTargetRow.CreateCell(m);
                //firstTargetCell.Encoding = firstSourceCell.Encoding;
                firstTargetCell.CellStyle = firstSourceCell.CellStyle;
                firstTargetCell.SetCellType(firstSourceCell.CellType);
            }
            #endregion
        }
        #endregion

        #region 页面参数获取
        protected T GetRequestValue<T>(string name)
        {
            return Request.GetRequestValue<T>(name);
        }

        protected T GetRequestValue<T>(string name, bool useDefValue, T defValue)
        {
            return Request.GetRequestValue<T>(name, useDefValue, defValue);
        }
        protected T GetRequestValue<T>(string name, T defValue)
        {
            return Request.GetRequestValue<T>(name, true, defValue);
        }
        #endregion

        #region 
        /// <summary>
        /// 排序字段 值为 id
        /// </summary>
        protected virtual string orderField
        {
            get
            {
                return GetRequestValue<string>("orderField", "");
            }
        }
        /// <summary>
        ///  排序方式 desc或 asc
        /// </summary>
        protected virtual string orderDirection
        {
            get
            {
                return GetRequestValue<string>("orderDirection", "desc");
            }
        }
        
        protected virtual string SQLSort
        {
            get
            {
                return orderField + " " + orderDirection;
            }
        }

        #endregion
        /// <summary>
        /// 获取工作表标题名，用于公式，多数用于自动生成标题列的情史
        /// </summary>
        /// <param name="cellNum">从0开始计数</param>
        /// <returns></returns>
        protected string GetCellName(int cellNum)
        {
            if (cellNum > 25)
            {
                int t = cellNum / 26;
                int tt = cellNum % 26;
                return Chr(t + 64) + Chr(tt + 65);
            }
            else
                return Chr(65 + cellNum);
        }
        private static string Chr(int asciiCode)
        {
            if (asciiCode >= 0 && asciiCode <= 255)
            {
                System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
                byte[] byteArray = new byte[] { (byte)asciiCode };
                string strCharacter = asciiEncoding.GetString(byteArray);
                return (strCharacter);
            }
            else
            {
                throw new Exception("ASCII Code is not valid.");
            }
        }

        #region 权限相关

        protected int UserId
        {
            get
            {
                return GetRequestValue<int>("uid", 0);
            }
        }       
        
        /// <summary>
        /// 应收帐款模块,可获取那些经销商权限处理
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>
        protected string FTradeAgentPowerSqlWhere(int UserId)
        {
            OUserInfo objU = OUserController.GetById(UserId);

            string DWZRel = "FTradeReceivablesListEasyUI";
            if (HasPower(DWZRel, new Permission[] { Permission.应收帐款_财务人员 }, objU))
            {
                return "";
            }
            if (HasPower(DWZRel, new Permission[] { Permission.应收帐款_风险人员 }, objU))
            {
                return "";
            }
            if (HasPower(DWZRel, new Permission[] { Permission.应收帐款_营业人员 }, objU))
            {
                return SAreaManagerAgentController.GetMyAgentSqlWhere(UserId);
            }
            return "";
        }

        #endregion       
    
    }
}